package com.rocksea.app.db.lowStrain;

import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;

import android.database.sqlite.SQLiteDatabase;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBaseConfig;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.SQLiteHelper;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.litesuits.orm.db.model.ColumnsValue;
import com.litesuits.orm.db.model.ConflictAlgorithm;

import com.mor.dataacquisition.vo.lowStrain.LowStrainData;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.StaticLoad.StaticLoad;
import com.rocksea.app.db.history.HistoryTable;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 吴志华 on 2017/7/27.
 *
 *
 */

public class DyDbHelper implements SQLiteHelper.OnUpdateListener {
    public static LiteOrm mDyDb;
    private static DyDbHelper mDyDbHelper;

    private DyDbHelper(Context context) {
        //初始化数据库
        DataBaseConfig config = new DataBaseConfig(context);
        config.dbName = Environment.getExternalStorageDirectory().getPath()+"/RailDatabase/db/LowStrainDb.db";
        config.dbVersion = 1;
        config.onUpdateListener = this;
        mDyDb = LiteOrm.newCascadeInstance(config);
        //mDyDb.setDebugged(true);
        LowStrainDb lowStrainDb = new LowStrainDb();
        lowStrainDb.lowStrainDataDb = new ArrayList<>();
        lowStrainDb.lowStrainDataDb.add(new LowStrainDb.LowStrainDataDb());
        mDyDb.insert(lowStrainDb);
        mDyDb.delete(lowStrainDb);
    }

    @Override
    public void onUpdate(SQLiteDatabase sqLiteDatabase, int i, int i1)
    {

        String sql = "Alter table "+"LowStrainDb"+" add column "+"inspectionFormId"+" TEXT ";
        sqLiteDatabase.execSQL(sql);
        sql = "Alter table "+"LowStrainDb"+" add column "+"pileId"+" TEXT ";
        sqLiteDatabase.execSQL(sql);
        sql = "Alter table "+"LowStrainDb"+" add column "+"inspectionFormNum"+" TEXT ";
        sqLiteDatabase.execSQL(sql);
    }


    public static DyDbHelper getInstance(Context context){
        if (mDyDb==null){
            synchronized (DyDbHelper.class){
                mDyDbHelper =new DyDbHelper(context);
            }
        }
        return mDyDbHelper;
    }




    public void save(LowStrainDb mLowStrainDb)
    {
        QueryBuilder<LowStrainDb> queryBuilder = new QueryBuilder<>(LowStrainDb.class);
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.class);
        whereBuilder.andEquals("uuid",mLowStrainDb.uuid);
        queryBuilder.where(whereBuilder);
        if ((int)mDyDb.queryCount(queryBuilder) == 0)
        {
            mDyDb.save(mLowStrainDb);
        }
        else
        {
            if (mLowStrainDb.lowStrainDataDb != null)
            {
                for (int i = 0; i < mLowStrainDb.lowStrainDataDb.size(); i++)
                {
                    save(mLowStrainDb.lowStrainDataDb.get(i));
                }
            }
        }
    }
    public void save(LowStrainDb.LowStrainDataDb t)
    {
        QueryBuilder<LowStrainDb.LowStrainDataDb> queryBuilder = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.andEquals("uuid",t.uuid);
        queryBuilder.where(whereBuilder);
        if ((int)mDyDb.queryCount(queryBuilder) == 0)
        {
            mDyDb.save(t);
            QueryBuilder<LowStrainDb.LowStrainDataDb> queryCount = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
            queryCount.whereEquals("baseInfoId",t.baseInfoId);
            long count = mDyDb.queryCount(queryCount);

            WhereBuilder m = new WhereBuilder(LowStrainDb.class);
            m.andEquals("uuid",t.baseInfoId);
            mDyDb.update(m,new ColumnsValue(new String[]{"sampleNumber"},new String[]{String.valueOf(count)}),ConflictAlgorithm.Fail);

            // 新数据变化
            String sql = "UPDATE LowStrainDb SET upLoadTime = ? WHERE uuid = ?";
            mDyDb.getWritableDatabase().execSQL(sql,new String[]{String.valueOf(0),t.baseInfoId});
            DbCenter.mHistoryDbHelper.makeUnUpLoad(t.baseInfoId);

        }
    }

    public long queryCount(QueryBuilder<LowStrainDb.LowStrainDataDb> queryCount)
    {
        return mDyDb.queryCount(queryCount);
    }

    public ArrayList<LowStrainDb> qurey(){
        return mDyDb.query(LowStrainDb.class);
    }

    /**
     *按baseInfoId 删除数据
     *
     * */
    public void delete(String baseInfoId)
    {
        WhereBuilder lowDataWhereBuilder = new WhereBuilder(LowStrainDb.class);
        lowDataWhereBuilder.where("uuid LIKE ?",new Object[]{baseInfoId});
        mDyDb.delete(lowDataWhereBuilder);

        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.where("baseInfoId LIKE ?",new Object[]{baseInfoId});
        mDyDb.delete(whereBuilder);
    }

    /**
     * 按UUID查询数据库
     * */
    public ArrayList<LowStrainDb> queryByBaseInfoId(String baseInfoId,int a)
    {
        QueryBuilder<LowStrainDb> queryBuilder = new QueryBuilder<>(LowStrainDb.class);
        WhereBuilder whereBuilder = new WhereBuilder(HistoryTable.class);
        whereBuilder.where("uuid LIKE ?",baseInfoId);
        queryBuilder.where(whereBuilder);
        return mDyDb.query(queryBuilder);
    }

    public boolean isAllUploaded(String baseInfoId)
    {
        String sql = "select serviceId from LowStrainDb where uuid = ?";
        Cursor cursor = mDyDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int serviceId = cursor.getInt(cursor.getColumnIndex("serviceId"));
            cursor.close();
            if (serviceId > 0)
            {
                sql = "select upLoadTime from LowStrainDataDb where baseInfoId = ?";
                cursor = mDyDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
                if (cursor.moveToFirst())
                {
                    do {
                       Long upLoadTime =  cursor.getLong(cursor.getColumnIndex("upLoadTime"));
                       if (upLoadTime <= 0)
                       {
                           cursor.close();
                           return false;
                       }
                    }while (cursor.moveToNext());
                }
                cursor.close();
                return true;
            }
            else
                return false;
        }
        return false;

    }

    public boolean isWaveDataUpLoad(String uuid)
    {
        String sql = "select upLoadTime from LowStrainDataDb where uuid = ?";
        Cursor cursor = mDyDb.getWritableDatabase().rawQuery(sql,new String[]{uuid});
        if (cursor.moveToFirst())
        {
            Long upLoadTime = cursor.getLong(cursor.getColumnIndex("upLoadTime"));
            cursor.close();
            return upLoadTime > 0;
        }
        return false;

    }


    public LowStrainDb queryByBaseInfoId(String baseInfoId)
    {
        QueryBuilder<LowStrainDb> queryBuilder = new QueryBuilder<>(LowStrainDb.class);
        WhereBuilder whereBuilder = new WhereBuilder(HistoryTable.class);
        whereBuilder.where("uuid LIKE ?",baseInfoId);
        queryBuilder.where(whereBuilder);
        ArrayList<LowStrainDb> lowStrainDbs = mDyDb.query(queryBuilder);
        if (lowStrainDbs.size()==0)
            return null;
        if (lowStrainDbs.get(0).lowStrainDataDb == null)
        {
            lowStrainDbs.get(0).lowStrainDataDb  = (ArrayList<LowStrainDb.LowStrainDataDb>) mDyDbHelper.queryWaveData(baseInfoId);
        }
        return lowStrainDbs.get(0);
    }

    public void saveWaveData(LowStrainDb.LowStrainDataDb waveData)
    {
        mDyDb.insert(waveData);
    }

    public List<LowStrainDb.LowStrainDataDb> queryWaveData(String baseInfoId)
    {

        QueryBuilder<LowStrainDb.LowStrainDataDb> queryBuilder = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.where("baseInfoId LIKE ?",baseInfoId);
        queryBuilder.where(whereBuilder);
        return mDyDb.query(queryBuilder);
    }

    /**
     * @param isValid 是否只查询有效数据
     * */
    public  List<LowStrainDb.LowStrainDataDb> queryWaveData(String baseInfoId,boolean isValid)
    {

        QueryBuilder<LowStrainDb.LowStrainDataDb> queryBuilder = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
        queryBuilder.whereEquals("baseInfoId",baseInfoId);
        if (isValid)
        {
            queryBuilder.whereAppendAnd();
            queryBuilder.whereEquals("isValid",0);
        }
        return  mDyDb.query(queryBuilder);
    }

    public LowStrainDb.LowStrainDataDb queryWaveDataByUUId(String baseInfoId,String uuid)
    {
        QueryBuilder<LowStrainDb.LowStrainDataDb> queryBuilder = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
        queryBuilder.whereEquals("baseInfoId",baseInfoId);
        queryBuilder.whereAnd("uuid",uuid);
        List<LowStrainDb.LowStrainDataDb> lowStrainDataDb = mDyDb.query(queryBuilder);
        if (lowStrainDataDb.size()==0)
            return null;
        else
            return lowStrainDataDb.get(0);
    }

    /**
     * 对于每次敲击传输到手机的低应变
     * 查询方法
     * @param baseInfoId  基本信息的baseInfoId
     *
     * */
    public LowStrainDb queryLowStarinData(String baseInfoId)
    {
        LowStrainDb lowStrainData = queryByBaseInfoId(baseInfoId);
        if (lowStrainData.lowStrainDataDb==null)
        {
            lowStrainData.lowStrainDataDb = (ArrayList<LowStrainDb.LowStrainDataDb>) queryWaveData(baseInfoId,false);
        }
        return lowStrainData;
    }

    public LowStrainDb queryAllLowStarinData(String baseInfoId)
    {
        LowStrainDb lowStrainData = queryByBaseInfoId(baseInfoId);
        if (lowStrainData.lowStrainDataDb==null)
            lowStrainData.lowStrainDataDb = new ArrayList<>();
        lowStrainData.lowStrainDataDb = (ArrayList<LowStrainDb.LowStrainDataDb>) queryWaveData(baseInfoId);
        return lowStrainData;
    }

    /**
     * 更新指定的通道数据是否上传
     *
     * */
    public void makeWaveDataAsUpLoaded(String uuid)
    {
        //String sql = "UPDATE LowStrainDataDb SET isLoad=? , upLoadTime =? WHERE (uuid=?)";
        //mDyDb.getWritableDatabase().execSQL(sql,new Object[]{1,new Date().getTime(),uuid});
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.andEquals("uuid",uuid);
        mDyDb.update(whereBuilder,columnsValue, ConflictAlgorithm.Fail);
    }

    public LowStrainDb queryById(long id)
    {
        return mDyDb.queryById(id,LowStrainDb.class);
    }

    public void makeAsUpLoad(String baseInfoId)
    {
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isLoad","upLoadTime"},new String[]{"1",String.format("%d",new Date().getTime())});
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.andEquals("uuid",baseInfoId);
        mDyDb.update(whereBuilder,columnsValue,ConflictAlgorithm.Fail);
    }





    public void deleteAll()
    {
        mDyDb.deleteAll(LowStrainDb.class);
    }


    public void makeAsIsValid(String uuid, int i)
    {
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.LowStrainDataDb.class);
        whereBuilder.andEquals("uuid",uuid);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"isValid"},new Object[]{i});
        int code = mDyDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);
        //EventBus.getDefault().post(code);
    }

    public void insertServiceId(String baseInfoId, int returnCode)
    {
        WhereBuilder whereBuilder = new WhereBuilder(LowStrainDb.class);
        whereBuilder.andEquals("uuid",baseInfoId);
        ColumnsValue columnsValue = new ColumnsValue(new String[]{"serviceId"},new Object[]{returnCode});
        mDyDb.update(whereBuilder, columnsValue, ConflictAlgorithm.Fail);

    }

    public List<LowStrainDb.LowStrainDataDb> qureyData() {
        return mDyDb.query(LowStrainDb.LowStrainDataDb.class);
    }

    public int queryServiceId(String baseInfoId)
    {
        String sql = "select serviceId from LowStrainDb where uuid = ?";
        Cursor cursor = mDyDb.getWritableDatabase().rawQuery(sql,new String[]{baseInfoId});
        if (cursor.moveToFirst())
        {
            int serviceId = cursor.getInt(cursor.getColumnIndex("serviceId"));
            cursor.close();
            return serviceId;
        }
        cursor.close();
        return -1;
    }

    public int queryLowStarinDataCount(String baseInfoId)
    {
        QueryBuilder<LowStrainDb.LowStrainDataDb> queryBuilder = new QueryBuilder<>(LowStrainDb.LowStrainDataDb.class);
        queryBuilder.whereEquals("baseInfoId",baseInfoId);
        return (int) mDyDb.queryCount(queryBuilder);
    }


}
